package com.itlong.cloud.utils.phonenumber;

import com.google.common.base.Joiner;
import com.itlong.cloud.POJO.DTO.property.PhoneNumAttributionGroundDTO;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * <desc>
 *     处理手机号码工具类
 * </desc>
 *
 * @createDate 2018/05/18
 */
public class PhoneNoHandlerUtil {

    private static final Logger LOG = LoggerFactory.getLogger(PhoneNoHandlerUtil.class);

    /**
     * <desc>
     *     处理手机号码归属地，外地+0，本地-0
     * </desc>
     *
     * @param projectCityName 项目地址所处城市名字
     * @param phoneNos 手机号码字符串，多个用逗号连接
     * @return 处理后的手机号码字符串，多个用逗号连接
     * @author wangzhi
     * @createDate 2018/05/18
     */
    public static String handlerPhoneNoLocationAdd0OrSub0(String projectCityName,String phoneNos){
        String resultPhoneNo = phoneNos;
        if (StringUtils.isBlank(projectCityName) || StringUtils.isBlank(phoneNos)){
            return resultPhoneNo;
        }
        try {
            List<String> beijing = Arrays.asList("东城区","西城区","朝阳区","丰台区","石景山区","海淀区","门头沟区","房山区","通州区","顺义区","昌平区","大兴区","怀柔区","平谷区","密云区","延庆区");
            List<String> tianjin = Arrays.asList("和平区","河东区","河西区","南开区","河北区","红桥区","东丽区","西青区","津南区","北辰区","武清区","宝坻区","滨海新区","宁河区","静海区","蓟州区");
            List<String> shanghai = Arrays.asList("黄浦区","徐汇区","长宁区","静安区","普陀区","虹口区","杨浦区","闵行区","宝山区","嘉定区","浦东新区","金山区","松江区","青浦区","奉贤区","崇明区");
            List<String> chongqing = Arrays.asList("万州区","涪陵区","渝中区","大渡口区","江北区","沙坪坝区","九龙坡区","南岸区","北碚区","綦江区","大足区","渝北区","巴南区","黔江区","长寿区","江津区",
                    "合川区","永川区","南川区","璧山区","铜梁区","潼南区","荣昌区","开州区","梁平区","武隆区","城口县","丰都县","垫江县","忠县","云阳县","奉节县","巫山县","巫溪县","石柱土家族自治县",
                    "秀山土家族苗族自治县","酉阳土家族苗族自治县","彭水苗族土家族自治县");
            List<String> hongkong = Arrays.asList("中西区","湾仔区","东区","南区","油尖旺区","深水埗区","九龙城区","黄大仙区","观塘区","北区","大埔区","沙田区","西贡区","荃湾区","屯门区","元朗区",
                    "葵青区","离岛区");
            List<String> aomen = Arrays.asList("花地玛堂区","圣安多尼堂区","大堂区","望德堂区","风顺堂区","嘉模堂区","圣方济各堂区","路氹城","澳门新城");
            if (beijing.contains(projectCityName)) {
                projectCityName = "北京市";
            } else if (tianjin.contains(projectCityName)) {
                projectCityName = "天津市";
            } else if (shanghai.contains(projectCityName)) {
                projectCityName = "上海市";
            } else if (chongqing.contains(projectCityName)) {
                projectCityName = "重庆市";
            } else if (hongkong.contains(projectCityName)) {
                projectCityName = "中国香港";
            } else if (aomen.contains(projectCityName)) {
                projectCityName = "中国澳门";
            }
            List<String> phoneList =  Arrays.asList(phoneNos.split(","));
            List<String> phoneResult = new ArrayList<>();
            for (String onePhoneNum:phoneList){
                String phoneCityName = getPhoneNumCity(onePhoneNum);
                if (StringUtils.isBlank(phoneCityName)){
                    phoneResult.add(onePhoneNum);
                    continue;
                }
                boolean isLocalPhoneNum = projectCityName.contains(phoneCityName);
                String onePhoneResult = onePhoneNum;
                if (isLocalPhoneNum || (projectCityName.equals("眉山市") && phoneCityName.equals("成都")) || (projectCityName.equals("成都市") && phoneCityName.equals("眉山"))){ //如果是本地手机，取消首位加0
                    onePhoneResult  = onePhoneNum.replaceAll("^(0+)", "");
                } else{ //如果不是本地手机，首位加0
                    onePhoneResult  = String.format("0%s",onePhoneNum.replaceAll("^(0+)", ""));
                }
                phoneResult.add(onePhoneResult);
            }
            if (!phoneList.isEmpty()){
                resultPhoneNo =  Joiner.on(",").join(phoneResult);
            }
        } catch (Exception e) {
            LOG.error(String.format("处理异地手机号码：%s失败",phoneNos),e);
            return resultPhoneNo;
        }
        return resultPhoneNo;
    }

    /**
     * <desc>
     *    向已购买的接口获取更精确的号码归属地,精确到市
     * </desc>
     *
     * @param  phoneNum 电话号码
     * @return 电话号码归属地名称
     * @author wangzhi
     * @createDate 2018/05/18
     */
    public static String getPhoneNumCity(String phoneNum){
        String phoneCityName = "";
        String checkPhoneNum = phoneNum.replaceAll("^(0+)", ""); //去掉首位可能存在的0
        String host = "https://api04.aliyun.venuscn.com";
        String path = "/mobile";
        String method = "GET";
        String appcode = "c1924a31f90e4259a8062060a9ad7c0d";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<>();
        querys.put("mobile",checkPhoneNum);

        try {
            HttpResponse response = HttpProtocolUtil.doGet(host, path, method, headers, querys);
            if (response != null && response.getEntity() != null) {
                Map<String, Object> jsonToMap = JsonUtil.JsonToMap(EntityUtils.toString(response.getEntity()));
                if (jsonToMap != null && !jsonToMap.isEmpty()){
                    PhoneNumAttributionGroundDTO phoneNumAttributionGroundDTO = JsonUtil.toObject(jsonToMap.get("data").toString(), PhoneNumAttributionGroundDTO.class);
                    if (StringUtils.isNotBlank(phoneNumAttributionGroundDTO.getCity())){
                        phoneCityName = phoneNumAttributionGroundDTO.getCity();
                    }
                    return phoneCityName;
                }
            }
            LOG.info("获取手机号码归属地失败！");
        } catch (Exception e) {
            LOG.error(String.format("获取手机号码:%s归属地异常",phoneNum),e);
            return phoneCityName;
        }
        return phoneCityName;
    }

}
